package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"red-book-admin/cache"
	"red-book-admin/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	take := c.PostForm("take")
	if title == "" || content == "" || img == "" || take == "" {
		c.JSON(200, gin.H{
			"code": 4000,

			"msg": "字段不能为空",
		})
		return
	}
	data := models.RedBook{

		Title:   title,
		Content: content,
		Img:     img,
		Take:    take,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "发布失败",
		})
		return
	}

	redis := "train_" + strconv.Itoa(int(data.ID))
	var reds models.RedBook
	models.DB.Where("id=?", data.ID).First(&reds)
	jsonData, _ := json.Marshal(reds)
	cache.Rdb.Set(cache.Ctx, redis, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var arr models.RedBook
	err := models.DB.Where("id=?", id).First(&arr).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "详情失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情成功",
		"list": arr,
	})
}
func Del(c *gin.Context) {
	id := c.Query("id")
	var arr models.RedBook
	redis := "redis_" + id
	models.DB.Where("id=?", id).Delete(&arr)
	cache.Rdb.Del(cache.Ctx, redis)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})

}
func List(c *gin.Context) {
	var arr []models.RedBook

	redis := "redis_"
	RedisData, _ := cache.Rdb.Get(cache.Ctx, redis).Result()
	if RedisData == "" {
		models.DB.Find(&arr)
		jsonData, _ := json.Marshal(&arr)
		cache.Rdb.Set(cache.Ctx, redis, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(RedisData), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}
